//
//  HSHttpBaseRequest.m
//  AFNetworking
//
//  Created by huang on 2018/8/16.
//

#import "HSHttpBaseRequest.h"
#import "HSHttpTool.h"
#import "HSHttpConfig.h"
#import "HSHttpCacheDB.h"

@implementation HSHttpBaseRequest

+ (instancetype)shareInstance
{
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

#pragma mark - 发送请求
#pragma mark post请求
- (void)postWithPath:(NSString *)path params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure
{
    [self postWithPath:path params:params isCache:NO success:success failure:failure];
}

- (void)postWithPath:(NSString *)path params:(NSDictionary *)params isCache:(BOOL)isCache success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure
{
    [self requestWithMethod:HSRequestMethodPOST path:path params:params isCache:isCache success:success failure:failure];
}

#pragma mark get请求
- (void)getWithPath:(NSString *)path params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure
{
    [self getWithPath:path params:params isCache:NO success:success failure:failure];
}

- (void)getWithPath:(NSString *)path params:(NSDictionary *)params isCache:(BOOL)isCache success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure
{
    [self requestWithMethod:HSRequestMethodGET path:path params:params isCache:isCache success:success failure:failure];
}

#pragma mark 请求(总)
- (void)requestWithMethod:(HSRequestMethod)method path:(NSString *)path params:(NSDictionary *)params isCache:(BOOL)isCache success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure
{
    //1.缓存key
    NSString *cacheKey = [HSHttpBaseRequest cacheKeyWithUrl:path params:params.mutableCopy];
    NSDictionary *tempParms = [self correntParams:params];

    //2.发送请求
    [self requestWithMethod:method path:path params:tempParms success:^(id responseObject) {
        if (success == nil) return ;
        success(responseObject);
        
        //判断是否需要存储缓存
        if (isCache) {
            [[HSHttpCacheDB sharedManager] insertItem:responseObject cacheKey:cacheKey];
        }
        
    } failure:^(NSError *error) {
        NSDictionary *cacheData = [[HSHttpCacheDB sharedManager] itemWithCacheKey:cacheKey];
        if (!cacheData) {
            if (failure == nil) return ;
            failure(error);
        }else {
            if (success == nil) return ;
            success(cacheData);
        }
    }];
}

- (void)requestWithMethod:(HSRequestMethod)method path:(NSString *)path params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure
{
    [HSHttpTool requestWithMethod:method path:path params:params success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        [self requestSuccessWithResponseObject:responseObject success:success failure:failure];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure == nil) return ;
        failure(error);
    }];
}

#pragma mark - private
#pragma mark 获取参数
- (NSDictionary *)correntParams:(NSDictionary *)params
{
    return params;
}

#pragma mark 请求成功处理
- (void)requestSuccessWithResponseObject:(id)responseObject success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure
{
    if([responseObject isKindOfClass:[NSDictionary class]]){
        [self analyticalData:responseObject success:success failure:failure];
    }else if (responseObject == nil || [responseObject isKindOfClass:[NSNull class]]) {
        NSString *domain = @"server return nil error";
        NSInteger errorCode = 500;
        NSError *error = [NSError errorWithDomain:domain code:errorCode userInfo:nil];
        if (failure) {
            failure(error);
        }
    }else{
        //使用上面方法序列化为空
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (jsonDict == nil) {
            NSString *domain = @"server return nil error";
            NSInteger errorCode = 500;
            NSError *error = [NSError errorWithDomain:domain code:errorCode userInfo:nil];
            if (failure) {
                failure(error);
            }
        }else {
            [self analyticalData:jsonDict success:success failure:failure];
        }
    }
}

- (void)analyticalData:(NSDictionary *)responseObject success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure
{
    if (success) {
        success(responseObject);
    }
}

#pragma mark 将传递进来的参数拼接成url
+ (NSString *)cacheKeyWithUrl:(NSString *)baseUrl params:(NSMutableDictionary *)params
{
    NSString *str = @"&";
    for(id key in params) {
        str = [str stringByAppendingString:key];
        str = [str stringByAppendingString:@"＝"];
        str = [str stringByAppendingString:[NSString stringWithFormat:@"%@",[params objectForKey:key]]];
        str = [str stringByAppendingString:@"&"];
    }
    
    if (str.length > 1) {// 处理多余的&以及返回含参url
        str = [str substringToIndex:str.length - 1];
        return [baseUrl stringByAppendingString:str];
    }
    return Nil;
}

@end
